package actual;

import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2022-10-27
 * Time: 20:44
 */

//案例三 查找文件内容的关键词 递归的进行查找
public class Demo3 {
    public static void main(String[] args) throws IOException {
        //先递归的遍历文件 并打开 读取内容 在进行字符串查找
        //1.输入要扫描的文件路径
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的路径: ");
        String rootDirPath = scanner.next();
        System.out.println("请输入要查找的关键词: ");
        String word = scanner.next();

        //检测路径是否存在
        File rootDir = new File(rootDirPath);
        if (!rootDir.isDirectory()){
            System.out.println("输入的路径有误!");
            return;
        }
        //2.递归的进行遍历
        scanDir(rootDir,word);

    }

    private static void scanDir(File rootDir, String word) throws IOException {
        //1.还是先列出 root当中有哪些内容
        File[] files = rootDir.listFiles();
        if (files == null){
            return;
        }
        //2.遍历每个元素 真对普通文件和目录进行分别处理
        for (File f:files) {
            if (f.isFile()){
                //针对文件进行查找
                if (containsWord(f,word)){
                    System.out.println(f.getCanonicalPath());
                }
            } else if (f.isDirectory()) {
                //正对目录进行递归
                scanDir(f,word);
            }
        }
    }

    private static boolean containsWord(File f, String word) {
        StringBuilder stringBuilder = new StringBuilder();
        //把f中的内容读出来放到一个StringBuilder中
        try(Reader reader = new FileReader(f)) {
            char[] buffer = new char[1024];
            while (true){
                int len = reader.read(buffer);
                if (len == -1){
                    break;
                }
                //把读到的结果放到stringBuilder中
                stringBuilder.append(buffer,0,len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        //indexOf 返回的是字串的下标 如果word在在当中不存在 那么就返回-1
        return stringBuilder.indexOf(word) != -1;
    }
}
